import { defineStore } from 'pinia'
import { setToken, removeToken } from '@/utils/auth'
//import { login, getInfo, logout } from '@/api/login' 这个是模拟数据的，不用了
import service from '@/utils/request'

/* 定义一个名为 useUserStore 的状态管理模块，
 * 状态管理模块主要用于处理用户的登录、获取信息和注销操作，并跟踪用户的状态信息
 */
export const useUserStore = defineStore({
	id: 'userInfo', //为这个状态管理模块设置一个唯一的 ID。
	state: () => ({
		token: null,
		userId: null,
		userName: null,
		avatar: null,
		nickName: null,
		permissions: [],
		roles: []
	}),
	actions: {
		/**
		 * Logs in the user with the provided user information.
		 * 定义一个 Login 动作，它接受一个 userInfo 对象作为参数，然后使用 login 函数尝试登录。
		 * 如果登录成功，它会使用 setToken 函数保存 token，并更新状态中的 token 字段。
		 * @param {Object} userInfo - The user information.
		 * @param {string} userInfo.username - The username of the user.
		 * @param {string} userInfo.password - The password of the user.
		 * @return {Promise} A promise that resolves when the user is successfully logged in.
		 *                   The promise will be rejected with an error if login fails.
		 */
		Login: function (userInfo) {
			const username = userInfo.username.trim()
			const password = userInfo.password

			return new Promise((resolve, reject) => {
				service
					.post('/wxapi/wxsys/login', {
						username: username,
						password: password
					})
					.then((res) => {
						setToken(res.token)
						this.token = res.token
						resolve()
					})
					.catch((error) => {
						reject(error)
					})
			})
		},
		/**
		 * Retrieves information using the provided token.
		 * 定义一个 GetInfo 动作，它接受一个 token 作为参数，然后使用
		 * getInfo 函数获取用户信息。如果成功，它会更新状态中的各个字段。
		 * @param {type} token - The token used to authenticate the request.
		 * @return {Promise} A Promise that resolves with the response data.
		 *         If the request fails, the Promise is rejected with an error.
		 */
		GetInfo: function (token) {
			return new Promise((resolve, reject) => {
				console.log('the token is ****:' + token)
				service
					.get('/wxapi/wxsys/info')
					//getInfo(token)
					.then((res) => {
						console.log('返回的USEINFo is ****:' + res.user)
						console.log(res.user.userId)
						this.avatar = res.user.avatar
						this.userId = res.user.userId
						this.userName = res.user.userName
						//this.nickName = res.user.nickName
						//this.permissions = res.data.permissions
						this.roles = res.user.roleIdList
						resolve(res)
					})
					.catch((error) => {
						reject(error)
					})
			})
		},
		LogOut: function () {
			return new Promise((resolve, reject) => {
				console.log('退出Logout成功！')
				//logout()
				service
					.post('/wxapi/wxsys/logout')
					.then(() => {
						this.token = null
						this.userId = null
						removeToken()
						resolve()
					})
					.catch((error) => {
						reject(error)
					})
			})
		}
	}
})
